package laba3;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.IOException;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;

public class EnterDialog extends JDialog{
    private JPanel contentPane;
    private JButton buttonOK;
    private JButton buttonCancel;
    private JTextField IPField;
    private JButton newGame;
    private Socket socket;

    // Листенеры и гуй
    public EnterDialog() {
        setContentPane(contentPane);
        setModal(true);
        getRootPane().setDefaultButton(buttonOK);

        buttonOK.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                onOK();
            }
        });

        buttonCancel.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                onCancel();
            }
        });

// call onCancel() when cross is clicked
        setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
        addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                onCancel();
            }
        });

// call onCancel() on ESCAPE
        contentPane.registerKeyboardAction(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                onCancel();
            }
        }, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
    }

    void main(String[] args) {
        EnterDialog dialog = new EnterDialog();
        dialog.pack();
        dialog.setVisible(true);
    }

    private void onOK() {
        try {
            try {
                if (IPField.getText().isEmpty()) {
                    JOptionPane.showMessageDialog(new JFrame(),"Введите IP-адрес.");
                    return;
                }
                SwingUtilities.invokeLater(new lab3(IPField.getText()));
                dispose();
            } catch (UnknownHostException e) {
                JOptionPane.showMessageDialog(new JFrame(),"Введите корректный IP-адрес.");
                return;
            } catch (SocketException e) {
                System.out.println("Неизвестная ошибка. Возможно, соединение было прервано");
                e.printStackTrace();
                System.exit(-1);
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (HeadlessException e) {
            System.out.println("Неизвестная ошибка при выводе сообщения.");
            e.printStackTrace();
            System.exit(-1);
        }
    }

    private void onCancel() {
        System.exit(0);
    }

}
